<template>
  <div id="search">
    <div class="search-input">
      <input type="text" placeholder="在这里写下你想寻找的" @keyup.enter="handleSearch" ref="searchInput">
      <span @click="$router.push('/found')">取消</span>
    </div>
    <div class="search-content" v-if="showContent">
      <div class="search-tab">
        <div class="nav-container" ref="navContainer" @touchstart="onDragStart" @touchmove="onDragMove"
          @touchend="onDragEnd" @mousedown="onDragStart" @mousemove="onDragMove" @mouseup="onDragEnd"
          @mouseleave="onDragEnd">
          <ul class="nav-list" :style="{ transform: `translateX(${translateX}px)` }">
            <li v-for="(item, index) in searchPageTab" :key="index" :class="{ active: currentIndex === index }"
              @click="handleNavClick(index, item)" ref="navItems">
              {{ item }}
            </li>
          </ul>
        </div>
      </div>

      <router-view />
    </div>

  </div>
</template>

<script>
import { mapMutations } from 'vuex';

export default {
  data() {
    return {
      searchPageTab: ["全部", "日签", "阅读", "收音机", "音乐", "书影", "作者/音乐人"],
      currentIndex: 0,
      translateX: 0,
      itemWidths: [],
      navListWidth: 0,
      containerWidth: 0,
      itemOffsets: [],
      isDragging: false,
      startX: 0,
      startTranslateX: 0,
      maxTranslateX: 0,
      showContent: false,//控制内容显示
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.calculateNavMetrics();
      this.setActiveByRoute();
      this.adjustPosition(this.currentIndex);
      this.updateMaxTranslateX();
    });

    window.addEventListener('resize', this.handleResize);
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },

  created() {
    this.handleResize = () => {
      this.$nextTick(() => {
        this.calculateNavMetrics();
        this.adjustPosition(this.currentIndex);
        this.updateMaxTranslateX();
      });
    };
    // console.log(this.showContent);
  },

  methods: {
    onDragStart(event) {
      this.isDragging = true;
      this.startX = event.type.includes('mouse') ? event.clientX : event.touches[0].clientX;
      this.startTranslateX = this.translateX;
      // event.preventDefault();
    },

    onDragMove(event) {
      if (!this.isDragging) return;
      const currentX = event.type.includes('mouse') ? event.clientX : event.touches[0].clientX;
      const diff = currentX - this.startX;
      let newTranslateX = this.startTranslateX + diff;
      if (newTranslateX > 0) newTranslateX = 0;
      if (newTranslateX < this.maxTranslateX) newTranslateX = this.maxTranslateX;
      this.translateX = newTranslateX;
      event.preventDefault();
    },

    onDragEnd() {
      this.isDragging = false;
    },

    updateMaxTranslateX() {
      this.maxTranslateX = Math.min(0, this.containerWidth - this.navListWidth);
    },

    calculateNavMetrics() {
      if (!this.$refs.navItems || !this.$refs.navContainer) return;
      this.itemWidths = this.$refs.navItems.map(item => item.offsetWidth);
      this.itemOffsets = [0];
      let offset = 0;
      for (let i = 1; i < this.itemWidths.length; i++) {
        offset += this.itemWidths[i - 1];
        this.itemOffsets.push(offset);
      }
      this.navListWidth = this.itemWidths.reduce((total, width) => total + width, 0);
      this.containerWidth = this.$refs.navContainer.offsetWidth;
    },

    setActiveByRoute() {
      const path = this.$route.path;
      const routeName = path.split('/').pop();
      const index = this.searchPageTab.findIndex(item => {
        return this.getRouteName(item) === routeName;
      });
      if (index !== -1) this.currentIndex = index;
    },

    handleNavClick(index, item) {
      if (this.currentIndex === index) return;
      this.currentIndex = index;
      this.adjustPosition(index);
      const routeName = this.getRouteName(item);
      this.$router.push(`/search/${routeName}`);
    },

    adjustPosition(index) {
      if (index <= 1 || index >= this.searchPageTab.length - 2) {
        this.handleEdgeItems(index);
      } else {
        this.centerItem(index);
      }
    },

    handleEdgeItems(index) {
      let newTranslateX = 0;
      if (index <= 1) {
        newTranslateX = 0;
      } else if (index >= this.searchPageTab.length - 2) {
        newTranslateX = this.containerWidth - this.navListWidth;
        if (newTranslateX > 0) newTranslateX = 0;
      }
      this.translateX = newTranslateX;
    },

    centerItem(index) {
      const itemCenter = this.itemOffsets[index] + this.itemWidths[index] / 2;
      const containerCenter = this.containerWidth / 2;
      let newTranslateX = containerCenter - itemCenter;
      if (newTranslateX > 0) newTranslateX = 0;
      const minTranslateX = this.containerWidth - this.navListWidth;
      if (newTranslateX < minTranslateX) newTranslateX = minTranslateX;
      this.translateX = newTranslateX;
    },

    // 映射搜索页子路由
    getRouteName(item) {
      const nameMap = {
        '全部': 'search-all',
        '日签': 'search-daily-sign',
        '阅读': 'search-reading',
        '收音机': 'search-radio',
        '音乐': 'search-music',
        '书影': 'search-book-movie',
        '作者/音乐人': 'search-author'
      };
      return nameMap[item] || item;
    },

    // 映射 mutation
    ...mapMutations(['SET_SEARCH_QUERY']),
    handleSearch() {
      // 获取输入值并去除空格
      const inputVal = this.$refs.searchInput.value.trim()
      // 验证非空
      if (inputVal) {
        // 提交到 Vuex
        this.SET_SEARCH_QUERY(inputVal)
        // 显示内容区域
        this.showContent = true;
      }
    }
  },

  watch: {
    $route() {
      this.setActiveByRoute();
      this.adjustPosition(this.currentIndex);
    },
    showContent(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.calculateNavMetrics();
          this.adjustPosition(this.currentIndex);
          this.updateMaxTranslateX();
        });
      }
    }
  }
}
</script>

<style scoped lang="less">
#search {
  width: 100vw;
  height: 100vh;
  position: absolute;
  top: 0;
  left: 0;
  background-color: #fff;
  z-index: 13;
  display: flex;
  flex-direction: column;
  -webkit-user-drag: none;

  .search-input {
    width: 100%;
    height: 6vh;
    padding: 1vh 2vw;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    gap: 2vw;
    background-color: #f8f8f8;
    position: relative;
    z-index: 1;

    input {
      background-color: #fff;
      height: 100%;
      width: 100%;
      font-size: 10px;
      padding: 0 2vw;
      box-sizing: border-box;
    }

    span {
      font-size: 10px;
      white-space: nowrap;
      font-weight: 300;
    }
  }

  .search-content {
    padding-top: 2vh;
    flex: 1;
    position: relative;
    overflow-x: hidden;

    .search-tab {
      width: 100%;
      height: 6vh;
      background-color: #fff;
      position: sticky;
      top: 0;
      z-index: 1;

      .nav-container {
        width: 100%;
        height: 100%;
        overflow: hidden;

        .nav-list {
          display: flex;
          height: 100%;
          transition: transform 0.3s ease;
          padding: 0;
          margin: 0;
          list-style: none;

          li {
            padding: 0 20px;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 15px;
            color: #333;
            white-space: nowrap;
            cursor: pointer;

            &.active {
              font-size: 17px;
              font-weight: bold;
              color: #000;
            }
          }
        }
      }

      >router-view {
        height: calc(100% - 6vh);
        overflow-y: auto;
        box-sizing: border-box;
      }
    }
  }
}
</style>